const app = getApp()

import axios from '../../utils/axios'

Page({

  data: {
    currentIndex: 0, // swiper的index
    navIndex: 1, // 商品介绍index
    couponState: false, // 领取优惠券模态框
    goodsId: '',
    goodsInfo: null, // 商品详情
    shopp: false, // 购买模态框
    serviceState: false, // 服务说明模态框
    mayCouponList: [], // 可领取优惠券list
    allCouponList: [], // 全部优惠券list
    passJson: {
      attachName: '规格',
      count: '数量'
    }, // 子组件传过来的规格JSON
    probablyMoney: '', // 销售价
    showCost: '', // 原价
    textList: [],
    imgList: [],
    eventInfo: '',
    shareShow: false, // 是否打开分享
  },

  onLoad: function (options) {

    this.setData({
      goodsId: decodeURIComponent(options.goodsId)
    })

    if (decodeURIComponent(options.key) != "undefined") {

      app.globalData.inviter = decodeURIComponent(options.key)

      wx.reLaunch({
        url: '/pages/login/login',
      })

    }

    this.selectCoupon()

    this.selectCommodityDetails()

  },

  onShow: function () {

  },

  // 选择规格数量
  selectAttachCount: function (e) {

    let goodsId = e.currentTarget.dataset.goodsid

    console.log("goodsInfo：================", this.data.goodsInfo)

    if (this.data.goodsInfo.goods_id == goodsId) {
      // 无规格，则给一个通用
      if (this.data.goodsInfo.attach == undefined || this.data.goodsInfo.attach.length <= 0) {
        let param = [{
          attach_id: '-1',
          name: '通用',
          discount: 0,
          price: this.data.goodsInfo.showMoney,
          showMoney: this.data.goodsInfo.showMoney,
          showSave: parseFloat(this.data.goodsInfo.showSave).toFixed(2),
          stock: this.data.goodsInfo.stock
        }]
        this.data.goodsInfo['attach'] = param
        this.setData({
          goodsInfo: this.data.goodsInfo,
          shopp: true
        })
      } else {
        for (let i = 0; i < this.data.goodsInfo.attach.length; i++) {
          let itemAttach = this.data.goodsInfo.attach[i]
          itemAttach['showMoney'] = itemAttach.discount > 0.01 ? itemAttach.discount : itemAttach.price
          itemAttach['showSave'] = parseFloat(itemAttach.price - itemAttach.showMoney).toFixed(2)
        }
        this.setData({
          goodsInfo: this.data.goodsInfo,
          shopp: true
        })
      }
    }
  },

  // 选择店铺商品
  changeCommodity: function (e) {
    this.setData({
      goodsId: e.currentTarget.dataset.goodsid
    })

    wx.pageScrollTo({
      scrollTop: 0
    })

    this.selectCommodityDetails()

  },

  // 查询商品详情
  selectCommodityDetails: function () {
    axios('/groupon/goodsDetail', {
      goods_id: this.data.goodsId
    }).then(res => {
      if (res.data.resultcode == 1) {

        app.disposeList(res.data.result.brand.goodsList)

        let info = res.data.result

        if (info.attach != undefined && info.attach.length > 0) {
          this.setData({
            showCost: info.attach[0].price,
            probablyMoney: info.attach[0].discount > 0.01 ? info.attach[0].discount : info.attach[0].price
          })
        } else {
          this.setData({
            showCost: info.price,
            probablyMoney: info.discount > 0.01 ? info.discount : info.price
          })
        }

        if (info.atlas.length == 0) {
          let json = {
            image: info.image
          }
          for (let i = 0; i < 3; i++) {
            info.atlas.push(json)
          }
        }

        const self = this
        let htmlContent = info.content;

        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
        let imgList = htmlContent.match(/<img.*?(?:>|\/>)/gi)

        let textReg = RegExp(/\<p\s?[^\>]*\>(?:(\s*)[^\s]+)\<\/p\>/g)
        let textList = htmlContent.match(textReg)

        let contentImg = []

        if (imgList) {
          for (var i = 0; i < imgList.length; i++) {
            let src = imgList[i].match(srcReg);
            //获取图片地址
            if (src[1]) {
              let field = {
                'show': false,
                'src': src[1]
              }
              contentImg.push(field)
            }
          }
        }

        if (textList) {
          for (var i = 0; i < textList.length; i++) {
            textList[i] = textList[i].substr(3, textList[i].length - 7)
            if (textList[i] == "&nbsp;") {
              textList[i] = "\n"
            }
          }
        }

        this.setData({
          textList: textList,
          imgList: contentImg,
          goodsInfo: app.disposeList(res.data.result)
        })

        setTimeout(() => {
          for (let i in contentImg) {
            wx.createIntersectionObserver().relativeToViewport({
              bottom: 100
            }).observe('.item-' + i, (result) => {
              if (result.intersectionRatio > 0) {
                contentImg[i].show = true
              }
              self.setData({
                imgList: contentImg,
              })
            })
          }
        }, 1000)

      }
    })
  },

  // 事件委托
  getUserInfo: function (e) {

    // 当接口返回‘请登录’时，showLogin就变为true，然后调用授权
    if (e.detail.userInfo && app.globalData.showLogin) {
      const self = this
      app.signin(e.detail, function (res) {
        app.globalData.showLogin = false

        // 当事件是点击领券
        if (self.data.eventInfo == "coupon") {
          self.selectCoupon()
          self.setData({
            couponState: true
          })
        }
      })
    }

  },

  // 进入品牌
  accessBrand: function (e) {
    wx.navigateTo({
      url: '/pages/brand/brand?brandId=' + e.currentTarget.dataset.brandid,
    })
  },

  // 选择规格成功，子组件传过来的事件
  selectEvent: function (e) {
    this.setData({
      passJson: e.detail.passJson
    })
  },

  // 点击服务说明
  getService: function () {
    this.setData({
      serviceState: true
    })
  },

  // 点击关闭服务说明
  closeService: function () {
    this.setData({
      serviceState: false
    })
  },

  // 阻止冒泡，此方法不能删
  stopService: function () { },

  // 查询优惠券
  selectCoupon: function () {
    axios('/groupon/coupons').then(res => {
      if (res.data.resultcode == 1) {

        let list = res.data.result.store
        let itemJson = []

        let notJson = []

        if (list != undefined && list.length > 0) {
          for (let i = 0; i < list.length; i++) {
            if (list[i].receive_status == 1) {
              itemJson.push(list[i])
            } else {
              notJson.push(list[i])
            }
          }
        }


        let tempList = itemJson.concat(notJson)

        this.setData({
          allCouponList: tempList,
          mayCouponList: itemJson.slice(0, 3)
        })

      }
    })
  },

  // 点击领取优惠券
  getCoupon: function () {

    if (app.globalData.userToken == '' || app.globalData.showLogin) {
      app.globalData.showLogin = true
      this.setData({
        eventInfo: "coupon"
      })
    } else {
      this.setData({
        couponState: true
      })
    }

  },

  // 点击购物车事件
  checkShopp: function () {
    wx.navigateTo({
      url: '/pages/shopp/shopp',
    })
  },

  // 点击分享事件
  checkShare: function () {

    if (app.globalData.userToken == '' || app.globalData.showLogin) {
      app.globalData.showLogin = true
      this.setData({
        eventInfo: "share"
      })
    } else {
      this.setData({
        shareShow: true
      })
    }

  },

  // 点击关闭优惠券弹框
  closeCoupon: function () {
    this.setData({
      couponState: false
    })
  },

  // 阻止优惠券模态框的事件冒泡，此方法不能删
  stopCoupon: function () { },

  // 切换商品介绍
  cutCommodity: function (e) {

    let index = parseInt(e.currentTarget.dataset.index)

    this.setData({
      navIndex: index
    })

  },

  // swiper滑动事件
  slideSwiper: function (e) {
    this.setData({
      currentIndex: e.detail.current
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.goodsInfo.name
    }
  }
})